<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="他表字段配置" @ok="handleSubmit">
    <a-spin :spinning="spinningLoading">
      <BasicForm @register="registerForm" />
    </a-spin>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { omit } from 'lodash-es';
  import { defHttp } from '/@/utils/http/axios';

  export default defineComponent({
    name: 'LinkTableFieldConfigModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const spinningLoading = ref(false);
      const linkTableOptions = ref([]);
      const fieldOptions = ref([]);
      let tableAndFieldsMap = {};
      let oldValue = {};
      const { createMessage: $message } = useMessage();
      const [registerModal, { closeModal }] = useModalInner(async (data) => {
        console.log('data', data);
        oldValue = Object.assign({}, data.record);
        tableAndFieldsMap = data.tableAndFieldsMap;
        await initLinkTableOptions();
        await setFieldsValue({ dictTable: data.record.dictTable });
        setTimeout(async () => {
          let otherValue = omit(data.record, 'dictTable');
          await setFieldsValue(otherValue);
          await clearValidate();
        }, 200);
      });
      async function initLinkTableOptions() {
        let fieldNames = Object.keys(tableAndFieldsMap);
        if (!fieldNames || fieldNames.length == 0) {
          linkTableOptions.value = [];
        } else {
          let arr = [];
          for (let name of fieldNames) {
            arr.push({
              text: tableAndFieldsMap[name].title,
              value: name,
            });
          }
          linkTableOptions.value = arr;
        }
      }
      async function handleChange(fieldName) {
        if (fieldName) {
          const { table, fields } = tableAndFieldsMap[fieldName];
          if (!table) {
            $message.warning('请先完善字段[' + fieldName + ']关联记录的配置');
            return;
          }
          const url = '/api-online/online/cgform/field/listByHeadCode';
          const dataList = await defHttp.get({ url, params: { headCode: table } });
          if (dataList && dataList.length > 0) {
            let arr = dataList.map((item) => {
              return {
                text: item.dbFieldTxt,
                value: item.dbFieldName,
              };
            });
            console.log('字段字典', arr);
            let fieldArray = fields.split(',');
            fieldOptions.value = arr.filter((item) => fieldArray.indexOf(item.value) > 0);
          } else {
            fieldOptions.value = [];
          }
        }
      }
      const formSchemas = [
        {
          label: 'rowKey',
          field: 'rowKey',
          component: 'Input',
          show: false,
        },
        {
          label: '字段描述',
          field: 'dbFieldTxt',
          component: 'Input',
          required: true,
        },
        {
          label: '关联记录',
          field: 'dictTable',
          component: 'JSearchSelect',
          required: true,
          componentProps: ({ formActionType }) => {
            let tempOptions = linkTableOptions.value;
            return {
              async: false,
              popContainer: '.link-table-field-config-modal',
              dictOptions: tempOptions,
              immediateChange: true,
              onChange: async (name) => {
                if (oldValue.dictText) {
                  await formActionType.setFieldsValue({
                    dictText: '',
                  });
                  await formActionType.clearValidate();
                }
                handleChange(name);
              },
            };
          },
        },
        {
          label: '显示字段',
          field: 'dictText',
          component: 'JSearchSelect',
          required: true,
          componentProps: {
            async: false,
            popContainer: '.link-table-field-config-modal',
            dictOptions: fieldOptions,
            onChange: (value) => {
              oldValue['dictText'] = value;
            },
          },
        },
      ];
      const [registerForm, { validate, setFieldsValue, clearValidate }] = useForm({
        schemas: formSchemas,
        showActionButtonGroup: false,
        labelAlign: 'right',
      });
      async function handleSubmit() {
        const data = await validate();
        console.log('handlesub', data);
        emit('success', data);
        closeModal();
      }
      return {
        registerModal,
        spinningLoading,
        registerForm,
        handleSubmit,
      };
    },
  });
</script>
<style scoped></style>
